package PageClassTable;

import PageTable.AddPage;
import PageTable.DeletePage;
import PageTable.QueryPage;
import PageTable.UpdataPage;
import page.Page;
import page.PageClass;
import utils.JdbcUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.Map;

public class PageClassTable extends Box {
    public PageClassTable(int power, String name) {
        super(BoxLayout.Y_AXIS);
        //创建按钮
        JPanel btnPanel =new JPanel();
        btnPanel.setMaximumSize(new Dimension(800,20));
        JButton addBtn=new JButton("添加");
        JButton updateBtn=new JButton("修改");
        JButton deleteBtn=new JButton("删除");
        JButton queryBtn=new JButton("查询");
        btnPanel.add(addBtn);
        btnPanel.add(updateBtn);
        btnPanel.add(deleteBtn);
        btnPanel.add(queryBtn);
        this.add(btnPanel);
        addBtn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AddPageClass.init(power);
            }
        });
        updateBtn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                UpdataPageClass.init(power);
            }
        });
        deleteBtn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DeletePageClass.init(power);
            }
        });
        queryBtn.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                QueryPageClass.init(power);
            }
        });
        String[] ts={"分类编号","分类名"};
        String[][] begin =data_update();
        JTable table =new JTable();
        table.setEnabled(false);
        DefaultTableModel model =new DefaultTableModel(begin,ts); // 新建一个默认数据模型
        JScrollPane scrollPane=new JScrollPane(table);
        table.setModel(model);
        add(scrollPane);
    }
    public String[][] data_update(){
        PageClass.jssum();
        int MX= PageClass.sum;
        String[][] data =new String[MX][2];
        int sum=0;
        List<Map<String, Object>> datas= JdbcUtils.JdbcQuery("SELECT * FROM page_class");
        for(Map<String,Object> map : datas){
            int id = 0;
            String name = null;
            for(String key : map.keySet()) {
                if (key.equals("page_class_id")) id = (int) map.get(key);
                if (key.equals("page_class_name")) name = (String) map.get(key);
            }
            data[sum][0]= String.valueOf(id);
            data[sum][1]= String.valueOf(name);
            sum++;
        }
        return data;
    }
}
